package com.neusoft.nep.PublicSupervisor.controller;

import com.neusoft.nep.common.AlertUtils;
import com.neusoft.nep.common.FileUtils;
import com.neusoft.nep.entity.PublicSupervisorUser;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.Map;

public class ChangePasswordController {
    @FXML
    private TextField txtPhoneNumber;
    @FXML
    private TextField txtBirthday;
    @FXML
    private TextField txtGender;
    @FXML
    private TextField txtNewPassword;
    @FXML
    private Button btnBack;
    @FXML
    private Button btnConfirm;

    public void confirmPassword() {
        String phoneNumber = txtPhoneNumber.getText();
        String birthday = txtBirthday.getText();
        String gender = txtGender.getText();
        String newPassword = txtNewPassword.getText();

        // 验证输入是否为空
        if (phoneNumber.isEmpty() || birthday.isEmpty() || gender.isEmpty() || newPassword.isEmpty()) {
            AlertUtils.showDialog("修改失败", "请填写所有信息");
            return;
        }

        // 验证密码强度(至少六位）
        if (newPassword.length() < 6) {
            AlertUtils.showDialog("修改失败", "密码至少需要6位");
            return;
        }

        // 从文件读取用户数据
        Map<String, PublicSupervisorUser> userMap = FileUtils.readMapObject("PublicSupervisorUser.txt");

        if (!userMap.containsKey(phoneNumber)) {
            AlertUtils.showDialog("修改失败", "手机号不存在");
            return;
        }

        // 验证用户信息
        PublicSupervisorUser user = userMap.get(phoneNumber);
        if (!birthday.equals(user.getBirthday()) || !gender.equals(user.getSex())) {
            AlertUtils.showDialog("修改失败", "身份验证失败，请检查输入信息");
            return;
        }

        // 更新密码
        user.setPassword(newPassword);
        userMap.put(phoneNumber, user);
        FileUtils.writeMapObject("PublicSupervisorUser.txt", userMap);

        AlertUtils.showDialog("修改成功", "密码已成功更新，请重新登录");
        try {
            backToLogin();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void backToLogin() throws IOException {
        Stage stage = (Stage) btnBack.getScene().getWindow();
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../View/Login.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }
}